
local activityKey = KEYS[1]
local existedKey = KEYS[2]

local sn = ARGV[1]
local userId = ARGV[2]
local seckillCount = tonumber(ARGV[3])
local currentMillisecond = tonumber(ARGV[4])

if redis.call('hexists', existedKey, userId) ~= 0 then
  return 1004
end

local activityStr = redis.call('hget', activityKey, sn)

if not activityStr then
  return 1001
end

local activity = cjson.decode(activityStr)

if activity['activityQuota'] < 1 then
  return 1003
end

if activity['seckillMaxCount'] < seckillCount then
  return 1002
end

if activity['startTime'] > currentMillisecond then
  return 1005
end

activity['activityQuota'] = activity['activityQuota'] - 1

redis.call('hset', activityKey, sn, cjson.encode(activity))
redis.call('hset', existedKey, userId, userId)

local result = {
  userId = userId,
  activityId = activity['id'],
  productId = activity['productId'],
  seckillPrice = activity['seckillPrice'],
  seckillCount = seckillCount,
  seckillTime = currentMillisecond
}

return {0, cjson.encode(result)}
